﻿using AutoMapper;
using MediatR;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.User;
using Provenance.Read.Api.Application.Command.User;
using Provenance.Read.Api.Dto.User;

namespace Provenance.Read.Api.Application.CommandHandler.User
{
    public class GetRoleListCommandHandler : IRequestHandler<GetRoleListCommand, ApiResult<PagingResult<IList<GetRoleListResponseDTO>>>>
    {
        private readonly IRoleRepository _roleRepository;
        private readonly IRolePermissionRepository _rolePermissionRepository;
        private readonly IPermissionRepository _permissionRepository;
        private readonly ILogger<GetRoleListCommandHandler> _logger;
        private readonly IMapper _mapper;
        public GetRoleListCommandHandler(IRoleRepository roleRepository, IRolePermissionRepository rolePermissionRepository, IPermissionRepository permissionRepository, ILogger<GetRoleListCommandHandler> logger, IMapper mapper)
        {
            _roleRepository = roleRepository;
            _rolePermissionRepository = rolePermissionRepository;
            _permissionRepository = permissionRepository;
            _logger = logger;
            _mapper = mapper;
        }
        public async Task<ApiResult<PagingResult<IList<GetRoleListResponseDTO>>>> Handle(GetRoleListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var list = await _roleRepository.GetAllAsync(x => !x.IsDeleted);
                var result = _mapper.Map<IList<GetRoleListResponseDTO>>(list);
                foreach (var role in result)
                {
                    var rolePermissionList = await _rolePermissionRepository.GetAllAsync(x => x.RoleId == role.RoleId&&!x.IsDeleted);
                    var RermissionIds = rolePermissionList.Select(x => x.PermissionId).ToArray();
                    var PermissionList = await _permissionRepository.GetAllAsync(x => RermissionIds.Contains(x.PermissionId)&&!x.IsDeleted);
                    string[] PermissionNames = PermissionList.Select(x => x.PermissionName).ToArray();
                    role.PermissionNames = string.Join(',', PermissionNames);
                }
                var responseList = result.OrderBy(x => x.RoleId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                var pagingResult = new PagingResult<IList<GetRoleListResponseDTO>>()
                {
                    TotalCount = result.Count(),
                    TotalPage = (int)Math.Ceiling(result.Count() * 1.0 / request.PageSize),
                    Data = responseList
                };
                return ApiResult<PagingResult<IList<GetRoleListResponseDTO>>>.Success(pagingResult);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error in GetRoleListCommandHandler.Handle: " + ex.Message);
                return ApiResult<PagingResult<IList<GetRoleListResponseDTO>>>.Failure("Error in GetRoleListCommandHandler.Handle: " + ex.Message);
            }
        }
    }
}
